/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.app.tabsresource.service.impl;

import cn.hutool.core.util.ObjectUtil;
import me.zhengjie.modules.app.tabsresource.domain.TabsResourceInfo;
import me.zhengjie.modules.app.tabsresource.domain.dto.TabsResourceInfoEditDto;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.app.tabsresource.repository.TabsResourceInfoRepository;
import me.zhengjie.modules.app.tabsresource.service.TabsResourceInfoService;
import me.zhengjie.modules.app.tabsresource.service.dto.TabsResourceInfoDto;
import me.zhengjie.modules.app.tabsresource.service.dto.TabsResourceInfoQueryCriteria;
import me.zhengjie.modules.app.tabsresource.service.mapstruct.TabsResourceInfoMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.SecurityUtils;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author Haojie Li
* @date 2021-03-01
**/
@Service
@RequiredArgsConstructor
public class TabsResourceInfoServiceImpl implements TabsResourceInfoService {

    private final TabsResourceInfoRepository tabsResourceInfoRepository;
    private final TabsResourceInfoMapper tabsResourceInfoMapper;

    @Override
    public Map<String,Object> queryAll(TabsResourceInfoQueryCriteria criteria, Pageable pageable){
        Page<TabsResourceInfo> page = tabsResourceInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(tabsResourceInfoMapper::toDto));
    }

    @Override
    public List<TabsResourceInfoDto> queryAll(TabsResourceInfoQueryCriteria criteria){
        return tabsResourceInfoMapper.toDto(tabsResourceInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public TabsResourceInfoDto findById(String id) {
        TabsResourceInfo tabsResourceInfo = tabsResourceInfoRepository.findById(id).orElseGet(TabsResourceInfo::new);
        ValidationUtil.isNull(tabsResourceInfo.getId(),"TabsResourceInfo","id",id);
        return tabsResourceInfoMapper.toDto(tabsResourceInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TabsResourceInfoDto create(TabsResourceInfo resources) {
        resources.setId(IdUtil.simpleUUID());

        resources.setCreateBy(SecurityUtils.getCurrentUsername());
        resources.setCreateTime(LocalDateTime.now());
        resources.setIsEnable(1);

        return tabsResourceInfoMapper.toDto(tabsResourceInfoRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TabsResourceInfo resources) {
    	resources.setUpdateBy(SecurityUtils.getCurrentUsername());
    	resources.setUpdateTime(LocalDateTime.now());
        TabsResourceInfo tabsResourceInfo = tabsResourceInfoRepository.findById(resources.getId()).orElseGet(TabsResourceInfo::new);
        ValidationUtil.isNull( tabsResourceInfo.getId(),"TabsResourceInfo","id",resources.getId());
        tabsResourceInfo.copy(resources);
        tabsResourceInfoRepository.save(tabsResourceInfo);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            tabsResourceInfoRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<TabsResourceInfoDto> all, HttpServletResponse response) throws IOException {
    	DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> list = new ArrayList<>();
        for (TabsResourceInfoDto tabsResourceInfo : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("资源地址", tabsResourceInfo.getResourceUrl());
            map.put("资源类型", tabsResourceInfo.getResourceType());
            map.put("资源显示位置（left、表示在左边显示资源，right、表示在右边展示的资源）", tabsResourceInfo.getResourceDisplayPosition());
//            map.put("所属选项卡id", tabsResourceInfo.getTabsId());
            map.put("所属酒店", tabsResourceInfo.getHotelName());
            map.put("所属选项卡", tabsResourceInfo.getTabsName());
            map.put("创建者", tabsResourceInfo.getCreateBy());
            map.put("更新者", tabsResourceInfo.getUpdateBy());
            map.put("创建时间", tabsResourceInfo.getCreateTime()  == null ? "" : dtf.format(tabsResourceInfo.getCreateTime()));
            map.put("更新时间", tabsResourceInfo.getUpdateTime() == null ? "" : dtf.format(tabsResourceInfo.getUpdateTime()));

            map.put("数据状态", tabsResourceInfo.getIsEnable());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }


    /**
     * 修改
     * @param tabsResourceInfoEditDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateX(TabsResourceInfoEditDto tabsResourceInfoEditDto) {
        //删除
        if(tabsResourceInfoEditDto.getIds().size()>0){
            tabsResourceInfoEditDto.getIds().forEach(i->{
                if(tabsResourceInfoRepository.findById(i).isPresent()){
                    tabsResourceInfoRepository.deleteById(i);
                }
            });
        }
        if(tabsResourceInfoEditDto.getResources().size()>0){
            tabsResourceInfoEditDto.getResources().forEach(i->{
                if(i.getId()==null){
                    i.setId(IdUtil.simpleUUID());
                    i.setCreateBy(SecurityUtils.getCurrentUsername());
                    i.setCreateTime(LocalDateTime.now());
                    i.setIsEnable(1);
                    tabsResourceInfoMapper.toDto(tabsResourceInfoRepository.save(i));
                }else {
                    i.setUpdateBy(SecurityUtils.getCurrentUsername());
                    i.setUpdateTime(LocalDateTime.now());
                    TabsResourceInfo tabsResourceInfo = tabsResourceInfoRepository.findById(i.getId()).orElseGet(TabsResourceInfo::new);
                    ValidationUtil.isNull( tabsResourceInfo.getId(),"TabsResourceInfo","id",i.getId());
                    tabsResourceInfo.copy(i);
                    tabsResourceInfoRepository.save(tabsResourceInfo);
                }
            });
        }

    }
}
